/**
 * 
 */
package pt.mleiria.saf;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;


/**
 * @author NB13712
 * 
 * Percorre os logs e conta quantas vezes determinado pan se tentou autenticar
 *
 */
public class PanMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
	
	private static final int MISSING = 9999;
	
	@Override
	protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
	
		final String line = value.toString();
		final String[] c101 = getC1o1(line);
		
		if(null != c101 && c101.length <= 12){
			System.out.println("c101[10]-->" + c101[10]);
			final String pan = null != c101[10] ? c101[10] : "";
			if(!pan.isEmpty()){
				context.write(new Text(pan), new IntWritable(1));
			}
		}
	}
	/**
	 * Tamanho: 12
	 * 0  --> C101
	 * 1  --> 
	 * 2  --> DateTime
	 * 3  --> Id do Pedido
	 * 4  --> Issuer do PAN
	 * 5  --> Cap Mode
	 * 6  --> 
	 * 7  --> 
	 * 8  --> TDS
	 * 9  --> Cap Token
	 * 10 --> PAN
	 * 11 --> Exp. Date
	 */
	private String[] getC1o1(final String logLine){
		Pattern pattern = Pattern.compile("<C101.+;>");
		Matcher matcher = pattern.matcher(logLine);
		if(matcher.find()){
			String c101 = matcher.group().substring(1, matcher.group().length()-1);
		    //System.out.println("c101-->" + c101);
		    String[] splitter = c101.split(";");
		    return splitter;
		}else{
			return null;
		}
	}
}
